<?php
/**
 * @author ran.ran
 * 取消系统订单同时取消支付订单及微信订单
 */

namespace services\models;
use Yii;
use leyestd\alipay\AlipayCloseOrder;
use Opwechat\Phppayment\Lib\WxPayOrderQuery;
use Opwechat\Phppayment\Lib\WxPayApi;
use Opwechat\Phppayment\Lib\WxPayCloseOrder;


class ClosePayment extends \common\models\PayLog
{  
   
   /**
    * 取消订单接口
    * @param string $out_trade_no 订单号
    * @param string $transaction_id 支付宝交易号|微信订单号
    */
   public function Close($out_trade_no,$transaction_id='') {
       
       $pay_log_info = self::find()->select(['order_sn','order_info_id','pay_id'])
                                   ->where(['order_sn'=>$out_trade_no])->one();
       if (!$pay_log_info) {
           return ['flag'=>false,'msg'=>'未查询到记录','errCode'=>'404'];
       }
       
       //支付宝
       if($pay_log_info->pay_id == 1) {
           
           $alipayOrder = new AlipayCloseOrder();
           $res = $alipayOrder->closeOrder($out_trade_no);
           if($res == 'T') {
              return ['flag'=>true,'msg'=>'取消支付宝订单成功','errCode'=>''];
           }
           
           return ['flag'=>false,'msg'=>'取消支付宝订单失败','errCode'=>'fail'];
       }
       
       //微信支付
       if($pay_log_info->pay_id == 5) {
           
           $inputObj = new WxPayOrderQuery();
           $inputObj->SetOut_trade_no($out_trade_no);
           
           $result = WxPayApi::orderQuery($inputObj);
           
           unset($inputObj);
           
           if(empty($result)) {
               
               return ['flag'=>false,'msg'=>'系统错误','errCode'=>'SYSTEMERROR'];
           }
           
           if(isset($result['err_code'])){
               
               return ['flag'=>false,'msg'=>$result['err_code_des'],'errCode'=>$result['err_code']];
           }
           
           if(isset($result['trade_state']) && $result['trade_state'] != 'NOTPAY') {

               return ['flag'=>false,'msg'=>$result['trade_state_desc'],'errCode'=>$result['trade_state']];
           }
           
           //未支付订单取消
           $inputObj = new WxPayCloseOrder();
           $inputObj->SetOut_trade_no($out_trade_no);
           
           $ret = WxPayApi::closeOrder($inputObj);
           
           if(isset($ret['err_code'])) {
               
               return ['flag'=>false,'msg'=>$ret['err_code_des'],'errCode'=>$ret['err_code']];
           }
           
           return ['flag'=>true,'msg'=>'取消微信订单成功','errCode'=>''];
       }

        return ['flag'=>false,'msg'=>'系统错误','errCode'=>'SYSTEMERROR'];
       
   }
}

?>